<template>
  <el-form class="login-form" status-icon :rules="loginRules" ref="loginForm" :model="loginForm" label-width="30px">
    <el-form-item prop="account">
      <el-input @keyup.enter.native="handleLogin" v-model="loginForm.account" auto-complete="off" placeholder="请输入账号"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input @keyup.enter.native="handleLogin" :type="passwordType" v-model="loginForm.password" auto-complete="off" placeholder="请输入密码">
        <i class="el-icon-view el-input__icon" slot="suffix" @click="showPassword"></i>
      </el-input>
    </el-form-item>

    <el-button type="primary" @click.native.prevent="handleLogin" class="login-submit">登录</el-button>

  </el-form>
</template>

<script>
export default {
  name: 'userLogin',
  data() {
    const validateaccount = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入账号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 1) {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      passwordType: 'password',
      loginForm: {
        account: 'admin',
        password: '111111'
      },
      loginRules: {
        account: [{ required: true, trigger: 'blur', validator: validateaccount }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      }
    }
  },
  mounted() {

  },
  methods: {
    handleLogin() {
      // 验证，只有信息符合规则才能进行下一步操作
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 调用user.js中的事件
          this.$store.dispatch('LoginByaccount', this.loginForm).then((res) => {
            // debugger
            if (res.code === 0) { // 返回的code为0，则表示登录成功，跳转页面
              location.href = '/'
            }
          }).catch(res => {
            this.$message.error(res.content)
          })
        } else {
          return false
        }
      })
    },
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '')
    }
  }
}
</script>
